import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {AppConfig} from '../../config';
import {Router} from '@angular/router';

const ignoreToken = ['login', 'logout', 'table'];

@Injectable()
export class CommonInterceptor implements HttpInterceptor {
  private skipAuth: string[];

  constructor(
    private router: Router
  ) {
    // 用户登录或认证请求则不需要添加头部AccessToken信息
    this.skipAuth = [
      `${AppConfig.APP_RESTFUL}/webapi/v1/auth/login`,
      `assets/config/config.json`,
      `assets/config/config_dev.json`,
    ];
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.isSkipAuth(request.url)) {
      request = request.clone({
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Authorization': '',
        })
      });
    } else {
      const access_token = sessionStorage.getItem('userToken').replace(/\"/g, '');
      if (request.body instanceof FormData) {
        request = request.clone({
          headers: new HttpHeaders({
            'Authorization': access_token,
          })
        });
      }else{
        request = request.clone({
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': access_token,
          })
        });
      }

    }
    return next.handle(request).pipe(
      tap(event => {
        if (event instanceof HttpResponse) {
          if (event.status >= 500) {
            // 跳转错误页面
          }
        }
      }, err => {
        if (err && (err.status == 401) && (err.statusText == 'Unauthorized')) {
          this.router.navigate(['/login']);
        }
      })
    );
  }

  /*
	 *是否跳过添加头部认证
	*/
  isSkipAuth(url: string) {
    let isMatch = false;
    this.skipAuth.forEach((reg_url: string) => {
      if (!isMatch) {
        if (url.search(reg_url) >= 0) {
          isMatch = true;
        }
      }
    });
    return isMatch;
  }
}
